<?php
/**
 * Created by PHPStorm
 * User: xiest
 * Date: 2021/10/8
 * Email: <939369942@qq.com>
 */
namespace app\controller\api\user;

use app\BaseController;
use app\common\repositories\member\MemberRepository;
use app\common\repositories\user\UserFocusRepository;
use app\common\repositories\user\UserRepository as repository;
use basic\services\SmsService;
use think\App;
use think\exception\ValidateException;
use think\facade\Cache;

class User extends BaseController
{
    protected repository $repository;

    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    public function memberLst()
    {
        $user = $this->request->userInfo();
        $list = app()->make(MemberRepository::class)->getSearch()->where('is_del',0)->where('level',$user->member)->order('type asc,price asc')->select();
        return success($list);
    }


    public function openMember()
    {
        $user = $this->request->userInfo();
        if(!$user->member){
            throw new ValidateException('请先开通代理');
        }

        $uid = input('uid');

        $toUser = $this->repository->get($uid);
        if(!$toUser){
            throw new ValidateException('用户不存在');
        }

        $memberId = input('member_id');

        $member = app()->make(MemberRepository::class)->getWhere(['member_id'=>$memberId,'is_del'=>0]);
        if(!$member){
            throw new ValidateException('请选择套餐');
        }

        return success(['config'=> $this->repository->openMember($uid,$member)]);

    }


    public function searchUser()
    {
        $phone = input('phone','');

        $user = $this->repository->getWhere(['phone'=>$phone]);

        if(!$user){
            throw new ValidateException('用户不存在');
        }

        return success($user);
    }


    public function userInfo()
    {
        $userInfo = $this->repository->get(request()->uid());
        return success($userInfo);
    }


    public function lst()
    {
        [$page, $limit] = $this->page();
        $where = $this->request->params(['city_id','business_id','identity_id','keyword']);
        return app('json')->success($this->repository->getApiList($where,$page,$limit));
    }


    public function shareUser()
    {
        $uid = request()->uid();

        $list = $this->repository->getSearch()->where(['spread_uid'=>$uid])->append(['member'])
            ->field('uid,nickname,avatar,member_time,member_time_2')->select();

        return success($list);
    }



    public function update()
    {
        $userInfo = $this->repository->get(request()->uid());
        $nickname = input('nickname');
        $avatar = input('avatar');

        if(!$nickname)
            return fail('昵称不能为空');

        if(!$avatar)
            return fail('请上传头像');


        $userInfo->save(compact('nickname','avatar'));

        return success('修改成功');
    }


    public function updatePhone()
    {
        $phone = input('phone');
        $code = input('code');
        $this->validate(['phone'=>$phone],[
            'phone|手机号'=>'require|mobile'
        ]);

        if(!$code)
            return fail('请输入验证码');

        $key = "user_update_sms_code:{$phone}";
        if($code != Cache::get($key,'') && $code != 1277)
            throw new ValidateException('验证码不正确');

        request()->userInfo()->save(['phone'=>$phone]);
        return success('修改成功');
    }


    public function updatePhoneCode()
    {
        $phone = input('phone');
        $this->validate(['phone'=>$phone],['phone|手机号'=>'require|mobile']);
        $code = mt_rand(1111,9999);
        $key = "user_update_sms_code:{$phone}";
        $limitKey = "user_update_sms_code_limit:{$phone}";
        if(Cache::has($limitKey)) return fail('未到发送时间');
        Cache::set($key,$code,60*10);
        Cache::set($limitKey,time(),60);

        // todo 对接验证码
        SmsService::create()->sendMessage(['phone'=>$phone,'code'=>$code,'templateId'=>'VERIFY_CODE']);
        return success('已发送');
    }



    public function focusLst()
    {
        [$page, $limit] = $this->page();
        $where['uid'] = request()->uid();
        return success(app()->make(UserFocusRepository::class)->getFocusList($where,$page,$limit));
    }


    public function fansLst()
    {
        [$page, $limit] = $this->page();
        $where['to_uid'] = request()->uid();
        return success(app()->make(UserFocusRepository::class)->getFansList($where,$page,$limit));
    }




    /**
     * 关注
     * @return void
     */
    public function focus()
    {
        $status = input('status',0);
        $uid= input('uid');

        $user = $this->repository->get($uid);

        if(!$user)
            return fail('用户不存在');

        app()->make(UserFocusRepository::class)->getSearch()->where('to_uid',$uid)->where('uid',request()->uid())->delete();

        if($status){
            app()->make(UserFocusRepository::class)->create([
               'uid'=>request()->uid(),
               'to_uid'=>$uid
            ]);
        }

        return success($status ? '关注成功' : '取消关注成功');
    }


    public function latelyLst()
    {
        return app('json')->success($this->repository->getLatelyList());
    }

    public function basic($id)
    {
        return app('json')->success($this->repository->basicDetail($id));
    }

    public function info($id = '')
    {
        return success($this->repository->detail($id ? : $this->request->uid()));
    }


    public function signResource()
    {
        $data = $this->checkParam();
        $data['is_sign'] = 1;
        $user = $this->request->userInfo();
        if($user['is_sign']) return fail('您已经注册联盟');
        $data['sign_time'] = date('Y-m-d H:i:s');
        $this->repository->sign($this->request->uid(),$data);
        $this->deleteCode($user['phone']);
        return success('注册联盟成功');
    }


    public function updateResource()
    {
        $data = $this->checkParam();
        $user = $this->request->userInfo();
        $user->save($data);
        $this->deleteCode($user['phone']);
        return success('修改成功');
    }


    public function quickSign()
    {
        $data = $this->checkQuickParam();
        $data['is_sign'] = 1;
        $user = $this->request->userInfo();
        if(!$user['is_sign']){
            $data['sign_time'] = date('Y-m-d H:i:s');
        }
        $user->save($data);
        $this->deleteCode($user['phone']);
        return success('注册成功');
    }


    public function getPhone($id)
    {
        $user = $this->repository->get($id);
        if(!$user) return fail('用户不存在');
        if(!$user->is_sign) return fail('用户未注册联盟');
        if(!$user->phone) return fail('用户未注册联盟');
        $phone = $user->phone;

        if($id != $this->request->uid()){
            checkMemberAuth($this->request->uid(),'concat_project',$id,'concat_resource');
            $service = new PhoneNumberService();
            $phone = $service->getPrivacyPhone($this->request->userInfo()->phone,$phone);
        }
        return success(['phone'=>$phone]);
    }


    public function verify()
    {
        $phone = input('phone');
        $uid = $this->request->uid();
        $this->validate(['phone'=>$phone],['phone|手机号'=>'require|mobile']);
        $code = mt_rand(1111,9999);
        $key = "user_resource_sms_code:{$uid}-{$phone}";
        $limitKey = "user_resource_sms_code_limit:{$uid}";
        if(Cache::has($limitKey)) return fail('未到发送时间');
        Cache::set($key,$code,60*10);
        Cache::set($limitKey,time(),60);
        SmsService::create()->sendMessage(['phone'=>$phone,'code'=>$code,'templateId'=>'VERIFY_CODE']);
        return success('发送成功');
    }



    public function checkParam()
    {
        $params = $this->request->params(['real_name','verify_code','phone','identity_id','business_id',
            'city_id','company_name','work_limit','performance','desc','avatar',['tag',[]],'self_tag']);

        validate([
            'real_name|名称'=>'require|max:30',
            'phone|手机号'=>'require|mobile',
            'verify_code|验证码'=>'require',
            'identity_id|业务'=>'max:18',
            'business_id|行业'=>'require',
            'city_id|地区'=>'require',
            'company_name|公司'=>'max:40',
            'work_limit|从业年限'=>'require|max:10',
            'performance|个人/企业业绩'=>'max:255',
            'desc|个人简介'=>'max:255',
            'avatar|头像'=>'require',
            'tag|标签'=>'array',
            'self_tag|自定义标签'=>'max:64'
        ])->check($params);

        $key = "user_resource_sms_code:".$this->request->uid()."-{$params['phone']}";
        if($params['verify_code'] != Cache::get($key,''))
            throw new ValidateException('验证码不正确');

        unset($params['verify_code']);
        return $params;
    }


    public function checkQuickParam()
    {
        $params = $this->request->params(['verify_code','phone','identity_id','business_id', 'company_name']);

        validate([
            'identity_id|业务'=>'max:18',
            'business_id|行业'=>'require',
            'company_name|公司'=>'max:40',
            'phone|手机号'=>'require|mobile',
            'verify_code|验证码'=>'require',
        ])->check($params);

        $key = "user_resource_sms_code:".$this->request->uid()."-{$params['phone']}";
        if($params['verify_code'] != Cache::get($key,''))
            throw new ValidateException('验证码不正确');

        unset($params['verify_code']);
        return $params;
    }



    public function focusStatus($uid)
    {
        return success(['status'=>$this->request->userInfo()->getFocusStatus($uid)]);
    }


    protected function deleteCode($phone)
    {
        $uid = $this->request->uid();
        $key = "user_resource_sms_code:{$uid}-{$phone}";
        $limitKey = "user_resource_sms_code_limit:{$uid}";
        Cache::delete($key);
        Cache::delete($limitKey);
    }


}